<?php

/*******************************************************************
 Zenith Picture Gallery
 Written by and copyright (c) Ali Almossawi
 http://www.cyberiapc.com

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License, a copy of 
 which is made available to you with this package.
 This program is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A  PARTICULAR PURPOSE.
 
 File: login.php
 Description: -
 Random quote: "Live your life as though your every act were to
 become a universal law." -Immanuel Kant
*******************************************************************/

session_start();
session_cache_expire(360);
require_once('config.php');
require_once('functions/f_global.php');
require_once('functions/f_db.php');

isIpBlacklisted(getenv("REMOTE_ADDR"), $config, $lang);

if (isset($_POST['submitLogin'])) {
   require_once('functions/f_db.php');

   $username = addslashes(dealWithSingleQuotes(charsEscaper($_POST['username'], $config['escape_chars'])));
   $password = addslashes(dealWithSingleQuotes(charsEscaper($_POST['password'], $config['escape_chars'])));
   
   if(!validateAlphaNumericFields(array($username,$password))) {
		 $redirect = "Location: login.php?status=0";
		 header("$redirect");
		 $_SESSION['msg'] = $lang['login_incorrect_msg'];
		 exit();
   }
   
   $statement = "SELECT uid, username, password, admin_status, approved, activated, cookie FROM {$config['table_prefix']}users WHERE username='$username'";
   $result = mysql_query($statement);
   $row = mysql_fetch_array($result);
   if(mysql_num_rows($result) > 0) {
		if($row['approved'] == 0 || $row['activated'] == 0) {
			$redirect = "Location: login.php?status=0";
			header("$redirect");
			$_SESSION['msg'] = $lang['login_awaiting_msg'];
			exit();
		}

		//if gallery is offline, only proceed if the user is an admin
		if($config['gallery_off']) {
			if($row['admin_status'] != "1") {
			   $redirect = "Location: login.php?status=0";
				 header("$redirect");
			   $_SESSION['msg'] = $lang['not_an_admin_msg'];
				 exit();
			}
		}

		//addslashes to the name in the table
		if(crypt($password, $row['password']) == $row['password'] && strcasecmp(addslashes($row['username']), $username) == 0 && strlen($username) > 0 && strlen($password) > 0) {
			//set cookies
			if(isset($_POST['remember_me'])) {
				$cookie_time = 86400 * 14; //expire after 2 weeks
				setcookie($config['cookie_prefix']."username", $row['username'], time() + $cookie_time,"/");
				setcookie($config['cookie_prefix']."hash", $row['cookie'], time() + $cookie_time,"/");
			}
			else {
				$cookie_time = 43200; //expire after 12 hours
				setcookie($config['cookie_prefix']."username", $row['username'], time() + $cookie_time,"/");
				setcookie($config['cookie_prefix']."hash", $row['cookie'], time() + $cookie_time,"/");
			}
			
			//session_regenerate_id(); //new in v0.8.8 (only supported in PHP 4.3.2+)
			$_SESSION["{$config['cookie_prefix']}_{$row['username']}"] = "1";
			$_SESSION["{$config['cookie_prefix']}_{$row['uid']}"] = "1";
			
			$redirect = "Location: redirecting.php";
			header("$redirect");
			exit();
		}
		else {
			$redirect = "Location: login.php?status=0";
			header("$redirect");
			$_SESSION['msg'] = $lang['login_incorrect_msg'];
			exit();
		}
   }//end if result
   else {
		$redirect = "Location: login.php?status=0";
		header("$redirect");
		$_SESSION['msg'] = $lang['login_incorrect_msg'];
		exit();
	}
   mysql_close($connection);
}
elseif (isset($_POST['submitUsername'])) {
	require_once('functions/f_db.php');
	$username = addslashes(dealWithSingleQuotes(charsEscaper($_POST['username'], $config['escape_chars'])));
	
	//resend activation email
	if($config['user_account_validation_method'] == 0) { //email
		$statement = "SELECT activation_key, email FROM {$config['table_prefix']}users WHERE username='".$username."'";
		$result = mysql_query($statement);
		$row = mysql_fetch_array($result);
		if($result) {
			$url = getCurrentInternetPath2($config,"register.php")."?username=$username&key={$row['activation_key']}";
			$body = "Hi $username,\n\nThank you for registering with us.  In order to start using your account, please activate it by clicking on the link below\n\n
			$url
			\n\nIf you feel that this email was sent in error, please forward it back as a reply.  This email was automatically generated by the Zenith Picture Gallery script from the IP address $users_ip.";
			$headers = "From: {$config['title']} <{$config['admin_email']}>\r\n";
			mail($row['email'],"{$config['title']} Activate your account",$body,$headers);
			//mailReloaded($row['email'],"",$config['admin_email'],$config['title'],"{$config['title']} Activate your account",$body);
		} 
		
		$redirect = "Location: login.php?do=resend_activation&sent=1";
	}
	else {
		$redirect = "Location: login.php?do=resend_activation&sent=0";
	}
	
	header("$redirect");
	exit();
}
elseif (isset($_POST['submitPasswordReset'])) {
	require_once('functions/f_db.php');
	$username = addslashes(dealWithSingleQuotes(charsEscaper($_POST['username'], $config['escape_chars'])));
	$email = dealWithSingleQuotes(charsEscaper($_POST['email'],$config['escape_chars']));
	
	$hash = str_replace(array("$","/","."),array("9","Z","E"),crypt(mt_rand()));;
	$hash_in_table = crypt($hash);
	
	//send password reset email
	$numrows = query_numrows("username","{$config['table_prefix']}users","username='".$username."' AND email='".$email."' AND admin_status != 1");
	if($numrows == "1") {
		//add hash to table
		$statement = "SELECT COUNT(username) AS n FROM {$config['table_prefix']}password_hashes WHERE username='".$username."'";
		$result = mysql_query($statement) or die(mysql_error());
		$row = mysql_fetch_array($result);
		
		$numrows = @query_numrows("uid","{$config['table_prefix']}users","username=\"{$_COOKIE[$cookie_name_username]}\" AND cookie=\"{$_COOKIE[$cookie_name_hash]}\"");
		
		if($numrows > "0") {
			$statement = "DELETE FROM {$config['table_prefix']}password_hashes WHERE username='".$username."'";
			$result = mysql_query($statement) or die(mysql_error());
		}
		
		$statement = "INSERT INTO `{$config['table_prefix']}password_hashes` ( `hid` , `hash` , `username`,  `hash_date`) 
		VALUES ('', '$hash_in_table', '$username', NOW())";
		$result = mysql_query($statement) or die(mysql_error());
		
		$statement = "SELECT hid FROM {$config['table_prefix']}password_hashes WHERE hash='".$hash_in_table."'";
		$result = mysql_query($statement) or die(mysql_error());
		$row = mysql_fetch_array($result);
		$hid = $row['hid'];
	
		//send email
		$url = getCurrentInternetPath2($config,"lost_password.php")."?hash=$hash"."&hid=$hid";
		$body = "Hi,\n\nWe received a request to change your password.  This email serves to verify that the request is in fact valid.  If it isn't, please report the IP address shown below to the administrator.  Otherwise, click on the link below to continue and select a new password.\n\n
		$url
		\n\nThis email was automatically generated by the Zenith Picture Gallery script from the IP address $users_ip.";
		$headers = "From: {$config['title']} <{$config['admin_email']}>\r\n";
		mail($email,"{$config['title']} Lost Password Request",$body,$headers);
		//mailReloaded($email,"",$config['admin_email'],$config['title'],"{$config['title']} Lost Password Request",$body);
		
		$redirect = "Location: login.php?do=forgot_password&sent=1";
	}
	else {
		$redirect = "Location: login.php?do=forgot_password&sent=0";
	} 
		
	header("$redirect");
	exit();
}



if(isset($_GET['do']) && $_GET['do'] == "resend_activation") {
	require_once('head.php');
	
	if($_GET['sent'] == "1") {
		//display success msg
		$_SESSION['sent_msg'] = $lang['activation_email_sent'];
	}
	else {
		echo "<table class='table_layout_sections' style='width:{$config['gallery_width']}' cellpadding='2' cellspacing='0'>
		<tr><td style='background-image:url(" . getSkinElement($config['stylesheet'], "images/td_back_mid.gif") . ")' class='cell_header' colspan='2'>{$lang['head_resend_activation']}</td></tr>
		<form name='frmResendActivation' enctype='multipart/form-data' action='{$_SERVER['PHP_SELF']}' method='post' style='margin-top:0;padding-top:0'>
		<tr><td width='100%' align='center'>
		<input type='text' name='username' class='textBox' style='width:50%' maxlength='64' />
		<input type='text' name='crypto' value='~".rand(128,999)."' class='textBox' style='width:38px' maxlength='3' DISABLED />
		</td></tr>
		<tr><td width='100%' align='center' class='cell_foot'>
		<input type='submit' name='submitUsername' value='{$lang['button_go']}' class='submitButton2' />
		</td></tr>
		</form>
		</table>
		";
		
		include('foot.php');
		exit();
	}
}
elseif(isset($_GET['do']) && $_GET['do'] == "forgot_password") {
	require_once('head.php');
	
	if($_GET['sent'] == "1") {
		//display success msg
		$_SESSION['sent_msg'] = $lang['forgot_pass_email_sent'];
	}
	else {
		echo "<form name='frmSendPasswordReset' enctype='multipart/form-data' action='{$_SERVER['PHP_SELF']}' method='post'>
		<table class='table_layout_sections' style='width:{$config['gallery_width']}' cellpadding='2' cellspacing='0'>
		<tr><td colspan='2' style='background-image:url(" . getSkinElement($config['stylesheet'], "images/td_back_mid.gif") . ")' class='cell_header' colspan='2'>{$lang['head_resend_password']}</td></tr>
		<tr><td width='40%'>{$lang['username']}</td><td width='60%'><input type='text' name='username' class='textBox' style='width:50%' maxlength='64' /></td></tr>
		<tr><td width='40%'>{$lang['email']}</td><td width='60%'><input type='text' name='email' class='textBox' style='width:50%' maxlength='64' /></td></tr>
		<tr><td width='100%' colspan='2' align='center' class='cell_foot'><input type='submit' name='submitPasswordReset' value='{$lang['button_go']}' class='submitButton2' /></td></tr>
		</table>
		</form>
		";
		
		include('foot.php');
		exit();
	}
}

//head_aware is used to add code to the head of a page
$head_aware['onload'] = "document.frmLogin.username.focus();";
require_once('head.php');

if(isset($_SESSION['msg'])) {
  echo "<div class='msg' style='color:red'>{$_SESSION['msg']}</div>";
  unset($_SESSION['msg']);
}
elseif(isset($_SESSION['sent_msg'])) {
  echo "<div class='msg'>{$_SESSION['sent_msg']}</div>";
  unset($_SESSION['sent_msg']);
}

echo "<table class='table_layout_sections' style='width:{$config['gallery_width']}' cellpadding='2' cellspacing='0'>
<tr><td style='background-image:url(" . getSkinElement($config['stylesheet'], "images/td_back_mid.gif") . ")' class='cell_header' colspan='2'>{$lang['head_login']}</td></tr>";
if($config['allow_registrations'] == "1") {
	echo "<tr><td class='search_page_cell'><span class='tiny_text_dark'>{$lang['register_notice']}";
	if($config['user_account_validation_method'] == "0") echo " <a href='login.php?do=resend_activation'>{$lang['resend_activation']}</a>";
	echo "</span><br /></td></tr>";
}

echo "<tr><td width='100%'>
<form name='frmLogin' enctype='multipart/form-data' action='{$_SERVER['PHP_SELF']}' method='post'>

<div class='columnLeft' style='width:45%'>
<div style='margin-bottom:14px; margin-left:5px;font-weight:bold'>{$lang['username']}</div>
<div style='margin-left:5px;font-weight:bold'>{$lang['password']}</div>
</div>

<div class='columnRight' style='width:55%'>
<div style='margin-bottom:10px'><input type='text' name='username' class='textBox' style='width:200px' maxlength='32' /></div>
<input type='password' name='password' class='textBox' style='width:200px' maxlength='12' /><br />
<span class='tiny_text'><a href='login.php?do=forgot_password'>{$lang['forgot_pass']}</a></span><br />
<input type='checkbox' name='remember_me' /> {$lang['remember_me']}<br />
</div>

<div align='center'><input type='submit' name='submitLogin' value='{$lang['button_login']}' class='submitButton2' style='margin-top:14px' /></div>
</form>
</td></tr>
</table>
";

include('foot.php');

?>